package net.vinote.smart.platform.service.timer;

import java.util.Date;

import net.vinote.smart.platform.comm.DateFunction;
import net.vinote.smart.platform.module.database.BeanEntityFactory;
import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBManagerFactory;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.module.security.PlatformSecurity;
import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.bean.CodeLibrary;
import net.vinote.smart.platform.service.enumerate.CodeCatalogEnum;
import net.vinote.smart.platform.timer.AbstractSmartTimerTask;

import org.json.JSONObject;

/**
 * License检测任务
 * 
 * @author Seer
 * @version CacheRefreshTask.java, v 0.1 2015年3月5日 下午2:32:15 Seer Exp.
 */
public class LicenseCheckTask extends AbstractSmartTimerTask {

	@Override
	public void run() {
		try {
			String hardwareAddress = PlatformSecurity.getHardwareAddress();
			DBManager bm = DBManagerFactory.getInstance("code_library");
			BizObject bo = bm
					.createQuery(SRE.getTable("code_library").getFieldsName(),
							"codeNo=? and itemNo=?")
					.setParamVal(CodeCatalogEnum.RegistrationCode.getCode(),
							hardwareAddress).getSingleResult();
			if (bo == null) {
				SRE.getInstance().setLicense(false);
				return;
			}
			CodeLibrary lib = new CodeLibrary();
			BeanEntityFactory.getInstance().getObject(lib, bo);
			JSONObject json = new JSONObject(lib.getAttr01());

			String registUser = json.getString("user");
			String expireDate = json.getString("expire");
			String token = json.getString("token");
			// 校验信息合法性
			String regCode = PlatformSecurity.generateRegistrationCode(
					registUser, expireDate);
			Date now = new Date();
			if (!token.equals(regCode)// 注册码正确
					|| DateFunction.getDate(expireDate, "yyyy-MM-dd")// 未过期
							.getTime() <= now.getTime()) {
				SRE.getInstance().setLicense(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
